import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_li_ke_jie/constant/app_constant.dart';
import 'package:flutter_li_ke_jie/entity/app_product.dart';
import 'package:flutter_li_ke_jie/style/common_color.dart';
import 'package:flutter_li_ke_jie/ui/home/home_model.dart';
import 'package:flutter_li_ke_jie/ui/web/web_view_page.dart';
import 'package:flutter_li_ke_jie/utils/log.dart';
import 'package:flutter_li_ke_jie/utils/navigator_util.dart';
import 'package:flutter_li_ke_jie/utils/sputil.dart';
import 'package:flutter_li_ke_jie/weight/horizontal_line_view.dart';
import 'package:flutter_li_ke_jie/weight/marquee_view.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';

import '../../core/interface/common_interface.dart';
import '../../router/router.dart';
import '../../utils/img_util.dart';

///首页卡片
class IndexFragment extends StatefulWidget {
  const IndexFragment({Key? key}) : super(key: key);

  @override
  _IndexFragmentState createState() => _IndexFragmentState();
}

class _IndexFragmentState extends State<IndexFragment> with CommonInterface<HomeModel>,WidgetsBindingObserver  {

  late HomeModel _homeModel;
  bool _isLoadData = false;//是否已经加载数据
  bool _isAuth = false;//是否认证
  @override
  void initState() {
    super.initState();
    _isLoadData = false;
    String? authState = SPUtil.getAuthState();
    Log.e("开始执行-->${authState}");
    if(authState!=null&&authState=="1"){
      setState(() {
        _isAuth = true;
      });
    }
  }


  @override
  Widget build(BuildContext context) {
    _homeModel = model(context);
    if(!_isLoadData){
      _isLoadData = true;
      _homeModel.getHomeProductList();
    }
    Log.e("页面build");
    return RefreshIndicator(
        onRefresh: _onRefresh,
        child: Container(
            color: color_f7,
            child: Column(
              children: [
                //标题
                _title(),
                //内容
                Expanded(
                  child: ListView(
                    padding: const EdgeInsets.only(top: 0, left: 10, right: 10),
                    children: [
                      //列表
                      Column(
                        children: [
                          ///头部标题和图片
                          _isAuth?_topAuthSuccessBanner():_topBanner(),
                          const SizedBox(
                            height: 10,
                          ),
                          _vipBox(),
                          const SizedBox(
                            height: 10,
                          ),

                          ///列表
                          _productListView(),
                          const SizedBox(
                            height: 10,
                          ),
                          _customerServiceView(),
                          const SizedBox(
                            height: 20,
                          ),
                        ],
                      )
                    ],
                  ),
                  flex: 1,
                )
              ],
            )));
  }

  //刷新
  Future<void> _onRefresh() async {
    //查询首页产品
    _homeModel.getHomeProductList();
  }

  ///标题
  Widget _title() {
    return Container(
        width: double.infinity,
        alignment: Alignment.center,
        child: Padding(
            padding: const EdgeInsets.only(top: 40, bottom: 20),
            child: Column(
              children: const [
                Text(
                  appName,
                  style: TextStyle(
                      color: color_1e,
                      fontSize: 20,
                      fontWeight: FontWeight.bold),
                ),
              ],
            )));
  }

  //头部卡片
  Widget _topBanner() {
    return GestureDetector(
      onTap: (){
        NavigatorUtil.go(context, REAL_NAME_PAGE).then((value){
          String? authState = SPUtil.getAuthState();
          if(authState!=null&&authState=="1"){
            setState(() {
              _isAuth = true;
            });
          }
        });
      },
      child: Image.asset(ImageUtil.loadLocalImg("hp_banner.png")),
    );
  }

  //头部填写完资料卡片
  Widget _topAuthSuccessBanner() {
    return Container(
      padding: EdgeInsets.only(left: 20,right: 20,top: 20,bottom: 20),
      decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("images/3.0x/loan_card.png",),
            fit: BoxFit.fill, // 完全填充
          )),
      child: Row(

        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: const [
                Text(
                  "最高可借(元)",
                  style: TextStyle(color: Colors.white, fontSize: 14),
                ),
                SizedBox(
                  height: 10,
                ),
                Text(
                  "200,000",
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 50,
                      fontWeight: FontWeight.bold),
                ),
                SizedBox(
                  height: 10,
                ),
                Text(
                  "年化利率(单利)7.2%-24%,1千元日均利息最低0.11元起",
                  style: TextStyle(color: Colors.white, fontSize: 14),
                ),
              ],
            ),
            flex: 2,
          ),
          Expanded(
            child: Container(
              child: MaterialButton(
                minWidth: 100,
                height: 40,
                color: Colors.white,
                shape: const RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                ),
                onPressed: () {
                  //产品列表页
                  NavigatorUtil.go(context, PRODUCT_PAGE);
                },
                child: Text(
                  "立即申请",
                  style: TextStyle(color: themeColor, fontSize: 16,fontWeight:FontWeight.bold),
                ),
              ),
            ),
            flex: 1,
          ),
        ],
      ),
    );
  }

  ///vip布局
  Widget _vipBox() {
    return Column(
      children: [
        //标题
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Text(
              "会员专属产品",
              style: TextStyle(
                  color: color_1e, fontSize: 18, fontWeight: FontWeight.bold),
            ),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text(
                  "查看更多",
                  style: TextStyle(color: color_999, fontSize: 16),
                ),
                Image.asset(
                  ImageUtil.loadLocalImg("next.png"),
                  height: 18,
                  width: 18,
                )
              ],
            )
          ],
        ),
        //卡片
        Row(
          children: [
            Expanded(
                flex: 1,
                child: Container(
                  margin: EdgeInsets.only(top: 10),
                  padding: EdgeInsets.only(top: 20, bottom: 20),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Image.network(_homeModel.headerVipAppProductList.elementAt(0).logoUrl.isNotEmpty?_homeModel.headerVipAppProductList.elementAt(0).logoUrl:zhanWeiPng,width: 50,height: 50,fit: BoxFit.fill),
                      SizedBox(
                        width: 20,
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "${_homeModel.headerVipAppProductList.elementAt(0).name}",
                            style: TextStyle(
                                color: color_1e,
                                fontSize: 16,
                                fontWeight: FontWeight.bold),
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                "最高",
                                style:
                                    TextStyle(color: color_999, fontSize: 14),
                              ),
                              SizedBox(
                                width: 3,
                              ),
                              Text("${_homeModel.headerVipAppProductList.elementAt(0).maxPrice}",
                                  style: TextStyle(
                                      color: color_fa2,
                                      fontSize: 14,
                                      fontWeight: FontWeight.bold)),
                              SizedBox(
                                width: 3,
                              ),
                              Text(
                                "元",
                                style:
                                    TextStyle(color: color_999, fontSize: 14),
                              ),
                            ],
                          )
                        ],
                      )
                    ],
                  ),
                )),
            SizedBox(
              width: 10,
            ),
            Expanded(
                flex: 1,
                child: Container(
                  margin: EdgeInsets.only(top: 10),
                  padding: EdgeInsets.only(top: 20, bottom: 20),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Image.network(_homeModel.headerVipAppProductList.elementAt(1).logoUrl.isNotEmpty?_homeModel.headerVipAppProductList.elementAt(1).logoUrl:zhanWeiPng,width: 50,height: 50,fit: BoxFit.fill),
                      SizedBox(
                        width: 20,
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "${_homeModel.headerVipAppProductList.elementAt(1).name}",
                            style: TextStyle(
                                color: color_1e,
                                fontSize: 16,
                                fontWeight: FontWeight.bold),
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                "最高",
                                style:
                                    TextStyle(color: color_999, fontSize: 14),
                              ),
                              SizedBox(
                                width: 3,
                              ),
                              Text("${_homeModel.headerVipAppProductList.elementAt(1).maxPrice}",
                                  style: TextStyle(
                                      color: color_fa2,
                                      fontSize: 14,
                                      fontWeight: FontWeight.bold)),
                              SizedBox(
                                width: 3,
                              ),
                              Text(
                                "元",
                                style:
                                    TextStyle(color: color_999, fontSize: 14),
                              ),
                            ],
                          )
                        ],
                      )
                    ],
                  ),
                )),
          ],
        )
      ],
    );
  }

  ///首页获取caed
  Widget _getCardWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text(
          "预估审批额度(元)",
          style: TextStyle(fontSize: 16, color: color_666),
        ),
        SizedBox(
          height: 10,
        ),
        Text("26000",
            style: TextStyle(
                fontSize: 50, color: color_333, fontWeight: FontWeight.bold)),
        SizedBox(
          height: 10,
        ),
        MaterialButton(
          height: 50,
          minWidth: 240,
          color: themeColor,
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(25)),
          ),
          onPressed: () {},
          child: Text("立即申请",
              style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.white)),
        ),
        SizedBox(
          height: 10,
        ),
        Text(
          "闪电下款,月息0.96%起,最长可借36期",
          style: TextStyle(fontSize: 16, color: color_666),
        ),
      ],
    );
  }

  ///跑马灯
  Widget _marquee() {
    return Container(
      height: 40,
      alignment: Alignment.center,
      child: Padding(
        padding: EdgeInsets.only(left: 20, right: 20),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.notifications_active),
            Expanded(
                flex: 1,
                child: Container(
                  alignment: Alignment.center,
                  child: Swiper(
                    itemHeight: 40,
                    scrollDirection: Axis.vertical,
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                          alignment: Alignment.centerLeft,
                          margin: EdgeInsets.only(left: 10),
                          child: Text(
                            "恭喜尾号xxx借款成功1000元",
                            style: TextStyle(color: color_333, fontSize: 16),
                          ));
                    },
                    //条目个数
                    itemCount: 6,
                    // 自动翻页
                    autoplay: true,
                    // 相邻子条目视窗比例
                    viewportFraction: 1,
                    loop: true,
                  ),
                ))
          ],
        ),
      ),
    );
  }

  List<String> _products = ["", "", "", ""];

  //产品列表
  Widget _productListView() {
    return Container(
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "产品列表",
            style: const TextStyle(
                color: color_333, fontSize: 18, fontWeight: FontWeight.bold),
          ),
          const SizedBox(
            height: 10,
          ),
          ListView.builder(
            padding: const EdgeInsets.only(top: 0),
            itemCount: _homeModel.homeAppProductList.length,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) {
              AppProduct? appProduct = _homeModel.homeAppProductList.elementAt(index);
              return _productItemView(context, index,appProduct);
            },
          )
        ],
      ),
    );
  }

  ///产品item
  Widget _productItemView(BuildContext context, int index,AppProduct appProduct) {
    return Container(
      padding: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
      decoration: BoxDecoration(color: Colors.white),
      margin: EdgeInsets.only(bottom: 10),
      child: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.network(
                appProduct.logoUrl,
                height: 36,
                width: 36,
                fit:BoxFit.fill ,
              ),
              const SizedBox(
                width: 10,
              ),
              Text(
                appProduct.name,
                style: TextStyle(
                    color: color_1e, fontSize: 16, fontWeight: FontWeight.bold),
              ),
              const SizedBox(
                width: 10,
              ),
              Expanded(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Text(
                      "日利率",
                      style: TextStyle(color: color_999, fontSize: 14),
                    ),
                    SizedBox(
                      width: 5,
                    ),
                    Text(
                      appProduct.dayRate,
                      style: TextStyle(color: color_999, fontSize: 14),
                    ),
                    SizedBox(
                      width: 2,
                    ),
                    Text("|", style: TextStyle(color: color_999, fontSize: 14)),
                    SizedBox(
                      width: 2,
                    ),
                    Text(
                      "期限",
                      style: TextStyle(color: color_999, fontSize: 14),
                    ),
                    SizedBox(
                      width: 5,
                    ),
                    Text(
                      "3~36月",
                      style: TextStyle(color: color_999, fontSize: 14),
                    ),
                  ],
                ),
                flex: 1,
              )
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                child: Row(
                  children: [
                    Text(
                      "${appProduct.maxPrice}",
                      style: TextStyle(
                          color: color_fa2,
                          fontSize: 28,
                          fontWeight: FontWeight.bold),
                    ),
                    SizedBox(
                      width: 5,
                    ),
                    Text(
                      "最高可借(元)",
                      style: TextStyle(color: color_999, fontSize: 14),
                    ),
                  ],
                ),
                flex: 1,
              ),
              MaterialButton(
                elevation: 0,
                minWidth: 120,
                height: 50,
                color: themeColor,
                shape: const RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                ),
                onPressed: () {
                  _homeModel.productClick(appProduct);
                  //跳转h5
                  Navigator.push(context,MaterialPageRoute(builder:
                      (BuildContext context)=> WebViewPage(url:appProduct.productUrl)));
                  //统计
                },
                child: Text("去申请",
                    style: TextStyle(color: Colors.white, fontSize: 18)),
              )
            ],
          ),
        ],
      ),
    );
  }

  //客服
  Widget _customerServiceView() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          "客服电话:",
          style: TextStyle(color: color_999, fontSize: 16),
        ),
        SizedBox(
          width: 2,
        ),
        Text(
          service_phone,
          style: TextStyle(color: themeColor, fontSize: 16),
        ),
      ],
    );
  }
}
